import React from "react";
import { Button, List, Avatar, Modal, Input, message } from "antd";
import { UserOutlined } from '@ant-design/icons';
import "./App.scss";
import MySocket from "./utils/MySocket";
import CharRoom from "./CharRoom";
import { TeamOutlined, LockOutlined } from '@ant-design/icons';

class App extends React.PureComponent {
  state = {
    visible: false,
    roomName: "",
    roomPass: "",
    userName: null,
    userId: null,
    userNameFlag: true,
    socket: null,
    joinVisible: false,
    joinRoomId: "",
    joinRoomPass: "",
    roomLists: [],
    joinRooms: {},
    joinSuccess: false,
    userList: [],
    messageList: [],
    myRoomsMess: new Map(),
    myUserRoomMess: {},
    currentUser: -1,
    currentRoom: {},
    kickOutFlag: false,
  };

  startConnect = (callback) => {
    const mySocket = new MySocket();

    const that = this;
    mySocket.connect("/");
    mySocket.getMessage("message", function (data) {
      if (!data) {
        message.error("error");
        return;
      }
      const { action } = data;
      if (action === "response2setName") {
        that.setState({
          userNameFlag: false,
        });
        message.info(data.msg)
      }
      if (action === "response2one2many") {
        const { joinRooms, myRoomsMess, userId, userName } = that.state;
        if (data.code === 1) {
          if (myRoomsMess.get(data.roomid)) {
            myRoomsMess.get(data.roomid).push({
              userId,
              userName: userName,
              msg: data.msg,
            });
          } else {
            myRoomsMess.set(data.roomid, [
              {
                userId,
                userName: userName,
                msg: data.msg,
              },
            ]);
          }
          console.log(myRoomsMess, joinRooms);
          that.setState({
            messageList: [...myRoomsMess.get(joinRooms.id)],
          });
        } else {
          message.error(data.msg);
          that.setState({
            joinSuccess: false
          })
        }
      }


      if (action === "youAreKicked") {
        that.setState({
          kickOutFlag: true
        })
      }

      if (action === "response2receiveOneToMany") {
        const { joinRooms, myRoomsMess } = that.state;
        if (data.code === 1) {
          if (myRoomsMess.get(data.roomid)) {
            myRoomsMess.get(data.roomid).push({
              userId: data.fromUser.id,
              userName: data.fromUser.name,
              msg: data.msg,
            });
          } else {
            myRoomsMess.set(data.roomid, [
              {
                userId: data.fromUser.id,
                userName: data.fromUser.name,
                msg: data.msg,
              },
            ]);
          }
          console.log(myRoomsMess);
          that.setState({
            messageList: [...myRoomsMess.get(joinRooms.id)],
          });
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2exitRoom") {
        if (data.code === 1) {
          that.setState({
            userList: [],
            joinSuccess: false,
          });
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2one2one") {
        const { myUserRoomMess, userId, userName } = that.state;
        if (data.code === 1) {
          let toUserId = data.toUser.id;
          let msgObj = {
            id: userId,
            name: userName,
            msg: data.msg,
          };
          if (myUserRoomMess[toUserId]) {
            myUserRoomMess[toUserId].push(msgObj);
          } else {
            myUserRoomMess[toUserId] = [msgObj];
          }

          that.setState({
            myUserRoomMess: { ...myUserRoomMess },
          });

          console.log(myUserRoomMess);
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2receiveMsg") {
        const { myUserRoomMess } = that.state;
        if (data.code === 1) {
          let fromUser = data.fromUser;
          let msgObj = {
            id: fromUser.id,
            name: fromUser.name,
            msg: data.msg,
          };
          if (myUserRoomMess[fromUser.id]) {
            myUserRoomMess[fromUser.id].push(msgObj);
          } else {
            myUserRoomMess[fromUser.id] = [msgObj];
          }

          that.setState({
            myUserRoomMess: { ...myUserRoomMess },
          });
          console.log(myUserRoomMess);
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2join") {
        const { joinRooms, myRoomsMess } = that.state;
        let newData = myRoomsMess.get(joinRooms.id);
        if (data.code === 1) {
          that.setState({
            userList: data.userList,
            joinVisible: false,
            joinSuccess: true,
            messageList: newData ? [...newData] : [],
          });
        } else {
          message.error(data.msg);
        }
      }

      if (action === "newUserJoined") {
        if (data.code === 1) {
          that.setState({
            userList: data.userList,
            joinVisible: false,
            joinSuccess: true,
          });
        } else {
          message.error(data.msg);
        }
      }

      if (action === "userListRefresh") {
        if (data.code === 1) {
          that.setState({
            userList: data.userList,
          });
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2refreshRoomList") {
        if (data.code === 1) {
          that.setState({
            roomLists: data.roomList,
            visible: false,
          });
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2connection") {

        if (data.code === 1) {
          that.setState({
            userId: data.id,
            roomLists: data.roomList,
            visible: false,
          });

          callback()
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2kick") {
        if (data.code === 1) {
          message.info(data.msg);
        } else {
          message.error(data.msg);
        }
      }
      if (action === "response2ban") {
        if (data.code === 1) {
          message.info(data.msg);
        } else {
          message.error(data.msg);
        }
      }

      if (action === "response2setBannedWords") {
        if (data.code === 1) {
        } else {
          message.error(data.msg);
        }
      }
      if (action === "response2createRoom") {
        that.setState({
          roomLists: data.roomList,
          visible: false,
        });
      }
    });

    this.setState({
      socket: mySocket,
    });
  };

  exiRoom = (roomId) => {
    this.state.socket.sendMessage({
      action: "exitRoom",
      params: [roomId],
    });
    this.setState({
      messageList: [],
    });
  };
  kick = (data) => {
    this.state.socket.sendMessage({
      action: "kick",
      params: data,
    });
  };
  ban = (data) => {
    this.state.socket.sendMessage({
      action: "ban",
      params: data,
    });
  };

  touchOne = (data) => {
    console.log(data);
    this.sendUserMess(data);
  };

  banWord = (data) => {
    this.state.socket.sendMessage({
      action: "setBannedWords",
      params: data,
    });
  };
  setName = (name) => {
    const that = this;

    if (!name || name.length < 1) {
      message.warning("plase input name!!")
    } else {
      this.startConnect(
        function () {
          that.state.socket.sendMessage({
            action: "setName",
            params: [name],
          });
        }
      )
    }
  };

  chargeRoom = (item) => {
    console.log(item);
    const { joinRooms } = this.state;

    if (joinRooms.id) {
      this.exiRoom(joinRooms.id);
    }
    this.setState({
      joinRooms: item,
      myUserRoomMess: {},
    });

    if (item.hasPwd) {
      this.setState({
        joinVisible: true,
      });
    } else {
      const { socket } = this.state;
      socket.sendMessage({
        action: "join",
        params: [item.id],
      });
    }
  };

  joinRoom = (item) => {
    const { joinRooms, joinRoomPass, socket } = this.state;
    socket.sendMessage({
      action: "join",
      params: [joinRooms.id, joinRoomPass],
    });
  };

  sendUserMess = (data) => {
    const { socket } = this.state;
    socket.sendMessage({
      action: "one2one",
      params: data,
    });
  };

  sendMess = (data) => {
    const { socket } = this.state;
    socket.sendMessage({
      action: "one2many",
      params: data,
    });
  };

  createRoom = () => {
    const { roomName, roomPass, socket } = this.state;
    socket.sendMessage({
      action: "createRoom",
      params: [roomName, roomPass],
    });
  };

  render() {
    const {
      roomLists,
      userName,
      roomName,
      roomPass,
      joinRoomPass,
    } = this.state;
    return (
      <div className='App'>
        <div className='leftContent'>
          <div
            className='person'
            onClick={() => {
              this.setState({ userNameFlag: true });
            }}
          >
            <Avatar size={64} icon={<UserOutlined />} />
            <span>{userName}</span>
          </div>

          <div className='roomCon'>
            <h3 style={{ textAlign: 'center', marginBottom: '0', marginTop: '15px' }}>Room List</h3>
            <List
              itemLayout='horizontal'
              dataSource={roomLists}
              renderItem={(item) => (
                <List.Item
                  style={{
                    display: "flex",
                    justifyContent: "center",
                    cursor: "pointer",
                  }}
                >
                  <Button
                    type={item.id === this.state.joinRooms.id ? "primary" : ""}
                    shape="round"
                    onClick={() => {
                      this.chargeRoom(item);
                    }}
                    icon={<>
                      {
                        item.hasPwd ? <LockOutlined /> : ''
                      }
                      <TeamOutlined />
                    </>}
                    block
                    style={{ marginRight: '10px' }}
                  >{item.name}</Button>
                </List.Item>
              )}
            />
          </div>

          <Button
            type="primary"
            onClick={() => {
              this.setState({ visible: true });
            }}
          >
            Create Chat Room
          </Button>
          <Modal
            title='Create Chat Room'
            visible={this.state.visible}
            onOk={this.createRoom}
            onCancel={() => {
              this.setState({ visible: false });
            }}
          >
            <div>
              RoomName
              <Input
                value={roomName}
                onChange={(value) => {
                  this.setState({
                    roomName: value.target.value,
                  });
                }}
              ></Input>
            </div>
            password
            <Input.Password
              value={roomPass}

              onChange={(value) =>
                this.setState({
                  roomPass: value.target.value,
                })
              }
            />
          </Modal>

          <Modal
            title='Join Room Validation'
            visible={this.state.joinVisible}
            onOk={this.joinRoom}
            onCancel={() => {
              this.setState({ joinVisible: false });
            }}
          >
            {/* <div>
              roomId
              <Input
                value={joinRoomId}
                onChange={(value) => {
                  this.setState({
                    joinRoomId: value.target.value,
                  });
                }}
              ></Input>
            </div> */}
            password
            <Input.Password
              value={joinRoomPass}
              onChange={(value) =>
                this.setState({
                  joinRoomPass: value.target.value,
                })
              }
            />
          </Modal>
        </div>

        <div className='rightContent'>
          {this.state.joinSuccess && (
            <CharRoom
              myUserRoomMess={this.state.myUserRoomMess}
              userId={this.state.userId}
              userList={this.state.userList}
              kick={this.kick}
              ban={this.ban}
              messageList={this.state.messageList}
              joinRooms={this.state.joinRooms}
              banWord={this.banWord}
              touchOne={this.touchOne}
              exiRoom={this.exiRoom}
              sendMess={this.sendMess}
            ></CharRoom>
          )}

          {!this.state.joinSuccess && (
            <div
              style={{
                width: "100%",
                height: "100%",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <h2>welcome to myChat</h2>
            </div>
          )}
        </div>

        <Modal
          onOk={() => this.setName(userName)}
          closable={false}
          footer={
            <Button
              type="primary"
              onClick={
                () => this.setName(userName)
              }>Submit</Button>
          }
          visible={this.state.userNameFlag}
        >
          userName:
          <Input
            value={userName}
            onKeyDown={e => {
              if (e.keyCode === 13) {
                this.setName(userName)
              }
            }}

            onChange={(e) =>
              this.setState({
                userName: e.target.value,
              })
            }
          ></Input>
        </Modal>

        <Modal visible={this.state.kickOutFlag}
          footer={
            <Button onClick={
              () => {
                this.setState({
                  kickOutFlag: false,
                  joinSuccess: false,
                })
              }
            }>sure</Button>
          }
        >

          <p>You got kicked out of here!!!</p>

        </Modal>

      </div>
    );
  }
}

export default App;
